<?php

/**
 * @author LSH 2013-03-15 
 *  豆瓣授权页 ..
 *  关于豆瓣的操作必须经过豆瓣授权之后才能进行..
 */
class Douban extends MY_Controller{
	
	public $m_openID  = 0;
	public $m_token   = null;
	public $m_retoken = null;
	public $m_outTime = null;
	public $m_name    = null;
	
	
	// 平台编号 ..
	public static $m_platformId = DOUBAN_TYPE;
	
	public function __construct()
	{
		parent::__construct();
		$this->load->config('oauth2');
		
		// 生成一个豆瓣Oauth类实例
		$config = $this->config->item('oauht2');
		$appConfig = $config['douban'];
		
		$this->load->library('Douban/MY_DoubanOauth',$appConfig);
			
		// 载入session
		$this->load->library('session');
		
		// 载入model
		$this->load->model('account/account_m');
	}
	public function index()
	{
		// 如果没有authorizeCode，跳转到用户授权页面
		if ( ! isset($_GET['code'])) {
			$this->my_doubanoauth->requestAuthorizeCode();
			exit;
		}
	
		
	}
	
	public function callback()
	{
		// 设置authorizeCode
		$this->my_doubanoauth->setAuthorizeCode($_GET['code']);
		
		// 通过authorizeCode获取accessToken，至此完成用户授权
		$arrDouban = $this->my_doubanoauth->requestAccessToken();
		
		// 授权成功
		if (is_array($arrDouban) || isset($arrDouban['access_token']))
		{
			$this->m_openID   = $arrDouban['douban_user_id'];
			$this->m_token    = $arrDouban['access_token'];
			$this->m_retoken  = $arrDouban['refresh_token'];
			$this->m_outTime  = $arrDouban['expires_in'];
			$this->m_name     = $arrDouban['douban_user_name'];
			

			// 写入session 中
				
			$newSession =  array(
					'openID' => $this->m_openID,
					'token'  => $this->m_token,
					'retoken'=> $this->m_retoken,
					'name'   => $this->m_name,
					'outTime'=> date('Y-m-d H:i:s',time() + (int)$this->m_outTime),
			);
			$this->session->set_userdata(array(SESSION_DOUBAN => $newSession));
			
			
			// 判断是否已经绑定 ...
			
			$filter = array(
					'openID' => $this->m_openID,
					'platformID' => self::$m_platformId,
					);
			
			
			
			$acc2platList = $this->account_m->getPlatfromList($filter);
			
			$this->oauth2($acc2platList);
		}
		
		
	}
}